package com.knife.member.stat;

import javax.servlet.Filter;
import javax.servlet.FilterConfig;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.FilterChain;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.StringTokenizer;

public class StatFilter
    implements Filter {
    public StatFilter() {
    }

    public void init(FilterConfig filtercfg) throws javax.servlet.
        ServletException {
    }
   
    public void doFilter(ServletRequest request,
                         ServletResponse response,
                         FilterChain filterchain) throws java.io.IOException,
        javax.servlet.ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpSession session = httpRequest.getSession(true);
        if (session.getAttribute("isRecorded") == null) {
            //如果本次用户访问还没有记录，就记录本次用户信息，并保存到数据库中
            session.setAttribute("isRecorded", Boolean.TRUE);
            //在session对象中保存一个变量"isRecorded"，并赋值
            String ip = httpRequest.getRemoteAddr();
            //从请求头中取出客户端IP地址
            String agent = httpRequest.getHeader("User-Agent");
            System.out.println("HTTP-HEAD: "+agent);
            //从请求头中读取User-Agent值
            StringTokenizer st = new StringTokenizer(agent, ";)");
            //构造StringTokenizer对象，使用“；”“）”来分解User-Agent值
            st.nextToken();
            String browser = st.nextToken();
            //得到用户的浏览器名
            String os = st.nextToken();
            //得到用户的操作系统名
            if (ip == null) {
                ip = "未知";
                //如果读取的IP为空，则赋值为“未知”
            }
            if (browser == null) {
                browser = "未知";
                //如果读取的浏览器名为空，则赋值为“未知”
            }
            if (os == null) {
                os = "未知";
                //如果读取的操作系统名为空，则赋值为“未知”
            }
            try {
                StatHandle.insert(ip,"" ,os.trim(), browser.trim(),"",0);
                //调用业务逻辑，将用户数据插入到数据库中
            }
            catch (Exception es) {
            }
        }
        filterchain.doFilter(request, response);
        //调用下一个过滤器或者直接调用JSP
    }

//  Mozilla/5.0 (Windows; U; Windows NT 5.0; zh-CN; rv:1.7.12) Gecko/20050919 Firefox/1.0.7
//  Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)
   
    public void destroy() {
    }
}
